package exercise;

import eventservice.Event;
import eventservice.EventChannel;
import eventservice.Proxy;
import eventservice.RemotelyPushable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

class PushConsumer extends UnicastRemoteObject implements RemotelyPushable {

	public PushConsumer() throws RemoteException {
		super();
	}

	public static void main(String[] args) {
		if (args.length < 2) {
			System.err.println("Usage: PushConsumer host channel_name");
			return;
		}

		String host = args[0];
		String channelName = args[1];

		Registry registry = null;
		try {
			registry = LocateRegistry.getRegistry(host);
		} catch (RemoteException e) {
			System.err.println("Cannot locate registry at host '" + host + "': " + e.getMessage());
			return;
		}

		EventChannel channel = null;
		try {
			channel = (EventChannel) registry.lookup(channelName);
		} catch (Exception e) {
			System.err.println("Cannot lookup channel '" + channelName + "': " + e.getMessage());
			return;
		}

		PushConsumer consumer;
		try {
			consumer = new PushConsumer();

			Proxy handle = null;
			try {
				handle = channel.subscribePushConsumer(consumer);
			} catch (RemoteException e) {
				System.err.println("Cannot subscribe consumer to channel '" + channelName + "': " + e.getMessage());
				return;
			}

			if (handle == null) {
				System.err.println("Consumer is already registered in '" + channelName + "'.");
				return;
			}

			Scanner scanner = new Scanner(System.in);
			scanner.nextLine();

			try {
				channel.unsubscribe(handle);
			} catch (RemoteException e) {
				System.err.println(
						"Cannot unsubscribe consumer from channel '" + channelName + "': " + e.getMessage());
			}

		} catch (RemoteException ex) {
			Logger.getLogger(PushConsumer.class.getName()).log(Level.SEVERE, null, ex);
		}

		System.exit(0);
	}

	@Override
	public void push(Event event) throws RemoteException {
		System.out.println(event);
	}
}
